const myRequest = require('../../utils/request.js'); // 导入整个模块
const app = getApp();
import Dialog from '@vant/weapp/dialog/dialog';
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '../../store/strategy/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo: [],
    city: '',
    strategy: [],
    timedata: [],
    mydata: [],
    mycollectdata: [],
    scrollTop: 0,
    topHeight: 0
  },
  // 滚动事件监听
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop,
    })
  },
  // getuserinfo(){
  //   myRequest.get('/api/')
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getuserinfo()
    this.setData({
      userinfo: JSON.parse(wx.getStorageSync('userinfo')),
      city: app.globalData.city
    })
    //在onload中创建
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['strategy'],
      actions: ['updatestrategy']
    })
    const {
      statusBarHeight
    } = wx.getSystemInfoSync();
    this.setData({
      topHeight: statusBarHeight + 40
    })
  },
  getmystrategy() {
    let that = this
    myRequest.get('/strategy/mystrategydata', {
      username: this.data.userinfo.username
    }).then(res => {
      // if (!res.data.status) {
      const strategy = res.data.map(item => ({
        ...item,
        avatar: app.globalData.baseAPI + item.avatar
      }))
      // 遍历数组A中的每个对象B
      strategy.forEach((item) => {
        item.like = JSON.parse(item.like)
        item.tag = JSON.parse(item.tag)
        item.collect = JSON.parse(item.collect)
      })

      that.setData({
        mydata: strategy,

      })
    }).catch(err => {
      console.error(err);
    });

  },
  getmycollct() {
    let that = this
    myRequest.get('/strategy/strategydata', {}).then(res => {
      const mycollectdata = []
      const strategy = res.data.map(item => ({
        ...item,
        avatar: app.globalData.baseAPI + item.avatar
      }))
      // 遍历数组A中的每个对象B
      strategy.forEach((item) => {
        item.tag = JSON.parse(item.tag)
        item.like = JSON.parse(item.like)
        item.collect = JSON.parse(item.collect)
        item.collect.forEach(val => {
          if (val.username == that.data.userinfo.username) {
            mycollectdata.push(item)
            return
          }
        })
      })
      that.setData({
        mycollectdata
      })
    }).catch(err => {
      console.error(err);
    });
  },
  replaceSpecialChar(content) {

    var regex = new RegExp('<img', 'gi')
    var delImgStyleReg = /(?<=\" )style=\".*?\"/gi;
    content = content.replace(delImgStyleReg, '')
    content = content.replace(regex, '<img style="width: 100%  !important";height:"auto  !important"')
    return content;

  },

  delete(e) {
    Dialog.confirm({
        message: '确定删除该攻略吗？',
      })
      .then(() => {
        let index = e.currentTarget.dataset.index
        let that = this
        myRequest.post('/strategy/delete', {
          id: this.data.mydata[index].id
        }).then(res => {
          wx.showToast({
            title: '删除成功！',
            icon: 'success'
          })
          setTimeout(() => {
            that.getmystrategy()
          }, 1000);
        }).catch(res => {
          wx.showToast({
            title: '删除失败！',
            icon: 'success'
          })
        })
      })
      .catch(() => {
        // on cancel
      });

  },
  update(e) {
    let index = e.currentTarget.dataset.index

    store.updatestrategy(this.data.mydata[index])

    wx.switchTab({
      url: '/pages/firstwrite/index',
    })
  },
  //攻略详情
  toastrategy(e) {
    const data = e.currentTarget.dataset.item
    data.islove = false
    data.iscollect = false
    let username = JSON.parse(wx.getStorageSync('userinfo')).username
    data.content = this.replaceSpecialChar(data.content)

    data.comment = JSON.parse(data.comment)
    data.like.forEach((element, index) => {
      if (username == element.username) {
        data.islove = true
      }
    });
    data.collect.forEach((element, index) => {
      if (username == element.username) {
        data.iscollect = true
      }
    });

    store.updatestrategy(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: '/packagesB/pages/astrategy/index',
    })
  },
  //更改用户信息
  updatemeaaage() {
    wx.navigateTo({
      url: '/packagesB/pages/updatemeaaage/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userinfo: JSON.parse(wx.getStorageSync('userinfo')),
      city: app.globalData.city
    })
    this.getmystrategy()
    this.getmycollct()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})